﻿using System;
using JetBrains.ReSharper.Daemon.Stages.Dispatcher;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using ReSharePoint.Basic.Inspection.Code.SPCAF;
using ReSharePoint.Basic.Inspection.Common.CodeAnalysis;
using ReSharePoint.Basic.Inspection.Common.Extensions;
using ReSharePoint.Common;
using ReSharePoint.Common.Attributes;
using ReSharePoint.Common.Consts;

[assembly: RegisterConfigurableSeverity(SPC020202Highlighting.CheckId,
  null,
  Consts.SPCAF_SECURITY_GROUP,
  SPC020202Highlighting.CheckId + ": " + SPC020202Highlighting.Message,
  "Setting this property to true opens security risks, potentially introducing cross-site scripting vulnerabilities.",
  Severity.WARNING,
  false, Internal = false)]

namespace ReSharePoint.Basic.Inspection.Code.SPCAF
{
    [ElementProblemAnalyzer(typeof(IAssignmentExpression),
        HighlightingTypes = new[] {typeof (SPC020202Highlighting)})]
    [Applicability(
        IDEProjectType.SP2010FarmSolution |
        IDEProjectType.SPSandbox |
        IDEProjectType.SP2013FarmSolution |
        IDEProjectType.SPServerAPIReferenced)]
    public class AvoidCallToAllowUnsafeUpdatesOnSPWeb : SPElementProblemAnalyzer<IAssignmentExpression>
    {
        protected override bool IsInvalid(IAssignmentExpression element)
        {
            bool result = false;

            IExpressionType expressionType = element.GetExpressionType();

            if (expressionType.IsResolved)
            {
                result = element.Dest.IsResolvedAsPropertyUsage(ClrTypeKeys.SPWeb, new[] { "AllowUnsafeUpdates" });
            }

            return result;
        }

        protected override IHighlighting GetElementHighlighting(IAssignmentExpression element)
        {
            return new SPC020202Highlighting(element);
        }
    }
    
    [ConfigurableSeverityHighlighting(CheckId, CSharpLanguage.Name, OverlapResolve = OverlapResolveKind.NONE, ShowToolTipInStatusBar = true)]
    public class SPC020202Highlighting : SPCSharpErrorHighlighting<IAssignmentExpression>
    {
        public const string CheckId = "SPC020202";
        public const string Message = "Avoid setting 'AllowUnsafeUpdates' on SPWeb";

        public SPC020202Highlighting(IAssignmentExpression element)
            : base(element, String.Format("{0}: {1}", CheckId, Message))
        {
        }

    }
}
